package com.rocksdata.mc.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.ctz.commonframe.ui.BaseActivity;
import com.ctz.commonframe.ui.BaseFragment;
import com.ctz.commonframe.ui.WebViewActivity;
import com.ctz.commonframe.ui.view.ptr.PullToRefreshBase;
import com.ctz.commonframe.ui.view.ptr.PullToRefreshScrollView;
import com.ctz.commonframe.utils.FullyLinearLayoutManager;
import com.ctz.commonframe.utils.RecycleViewDivider;
import com.rocksdata.mc.BuildConfig;
import com.rocksdata.mc.Constant;
import com.rocksdata.mc.business.BusinessManager;
import com.rocksdata.mc.business.UserInfoManager;
import com.rocksdata.mc.entity.NewsInfo2;
import com.rocksdata.mc.ui.adapter.WidgetNewsRecyclerAdapter;
import com.rocksdata.mc.R;
import com.rocksdata.mc.business.BusinessInterface;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 陈堂正 on 2017/4/8.
 */
@ContentView(R.layout.fragment_news)
public class NewsFragment extends BaseFragment {
    @ViewInject(R.id.lv_news)
    private PullToRefreshScrollView svNews;
    @ViewInject(R.id.rv_news)
    private RecyclerView rvNews;

    private List<NewsInfo2> newsInfoList = new ArrayList<>();
    private WidgetNewsRecyclerAdapter adapter;
    private int index = 1;

    @Override
    @SuppressWarnings("unchecked")
    public void onViewCreated(View view, Bundle savedInstanceState) {
        FullyLinearLayoutManager linearLayoutManager = new FullyLinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        rvNews.setNestedScrollingEnabled(false);
        rvNews.setLayoutManager(linearLayoutManager);
        rvNews.addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.HORIZONTAL, 2, getResources().getColor(R.color.light_gray)));

        adapter = new WidgetNewsRecyclerAdapter(mContext, newsInfoList);
        rvNews.setAdapter(adapter);

        svNews.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase refreshView) {
                index = 0;
                newsInfoList.clear();
                getNewsInfo();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase refreshView) {
                index++;
                getNewsInfo();
            }
        });
        adapter.setOnItemClickListener(new WidgetNewsRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Object item) {
                NewsInfo2 info = (NewsInfo2) item;
                String url;
                switch (info.getType()){
                    case NewsInfo2.NEWS_TYPE_VIDEO:
                        url = "file:///android_asset/pages/video.html?id=" + info.getNewsCode();
                        break;
                    default:
                        url = "file:///android_asset/pages/news.html?id=" + info.getNewsCode();
                        break;

                }
                try {
                    url = "file:///android_asset/www/index.html?baseUrl="
                            + URLEncoder.encode(BuildConfig.HOST, "UTF-8")
                            + "&apiToken=" + UserInfoManager.getAccessToken()
                            + "&userType=" + UserInfoManager.getCurrentUserType()
                            + "&userId=" + UserInfoManager.getCurrentUserId()
                            + "#/news/" + info.getNewsCode();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                Intent intent = new Intent(mContext, WebViewActivity.class);
                intent.putExtra(WebViewActivity.EXTRA_KEY_URL, url);
//                intent.putExtra(WebViewActivity.EXTRA_KEY_TITLE, "校内新闻");
                startActivity(intent);
            }
        });
        super.onViewCreated(view, savedInstanceState);

    }

    @Override
    protected void onVisible() {
        if(newsInfoList.size() == 0) {
            ((BaseActivity)mContext).showLoadingDialog();
        }
        getNewsInfo();
    }


    private void getNewsInfo(){
        Bundle datas = getArguments();
        if (datas == null) {
            ((BaseActivity)mContext).dismissLoadingDialog();
            return;
        }
        String tagId = datas.getString(Constant.EXTRA_KEY_NEWS_TAG);
        if (TextUtils.isEmpty(tagId)){
            ((BaseActivity)mContext).dismissLoadingDialog();
            return;
        }
        BusinessManager.getNewsManager().getNewsListByTag(tagId, index, new BusinessInterface.OnBusinessResultListener() {
            @Override
            public void onBusinessResult(boolean isSuccess, Object object, String message) {
                ((BaseActivity)mContext).dismissLoadingDialog();
                if(isSuccess){
                    @SuppressWarnings("unchecked")
                    List<NewsInfo2> list = (List<NewsInfo2>) object;
                    if(list != null && list.size() > 0){
                        for(NewsInfo2 info: list){
                            if(!newsInfoList.contains(info))
                                newsInfoList.add(info);
                        }
                        adapter.notifyDataSetChanged();
                        svNews.onRefreshComplete();
                        return;
                    }
                }
                if(index > 1)
                    index--;
                svNews.onRefreshComplete();
            }
        });


    }
}
